package com.example.tiaociweb.Controller;
import com.example.tiaociweb.Service.CeramicService;
import com.example.tiaociweb.entity.Ceramic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private CeramicService ceramicService;

    @GetMapping
    public String adminPage(Model model) {
        model.addAttribute("ceramics", ceramicService.findAll());
        return "admin";
    }

    @GetMapping("/new")
    public String newCeramicForm(Model model) {
        model.addAttribute("ceramic", new Ceramic());
        return "ceramic_form";
    }

    @PostMapping("/save")
    public String saveCeramic(@ModelAttribute Ceramic ceramic, RedirectAttributes redirectAttributes) {
        ceramicService.save(ceramic);
        redirectAttributes.addFlashAttribute("message", "陶瓷信息保存成功！");
        return "redirect:/admin";
    }

    @GetMapping("/edit/{id}")
    public String editCeramicForm(@PathVariable Long id, Model model) {
        Ceramic ceramic = ceramicService.findById(id);
        model.addAttribute("ceramic", ceramic);
        return "ceramic_form";
    }

    @GetMapping("/delete/{id}")
    public String deleteCeramic(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        ceramicService.deleteById(id);
        redirectAttributes.addFlashAttribute("message", "陶瓷信息删除成功！");
        return "redirect:/admin";
    }
}
